package ro.upt.dcda.pricezone.s2.requests;

import java.util.Set;

import javax.jms.JMSException;
import javax.jms.StreamMessage;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;

import ro.upt.dcda.pricezone.common.ConnectionFactory;
import ro.upt.dcda.pricezone.s2.pojo.ProductPrice;
import ro.upt.dcda.pricezone.s2.pojo.Store;

public class ProductInfoRequest implements S2Request {

	private int storeID;

	public ProductInfoRequest(StreamMessage request) throws JMSException {
		storeID = request.readInt();
	}

	@SuppressWarnings("unchecked")
	public void work(StreamMessage message) throws JMSException {
		Session session = ConnectionFactory.getFactory().openSession();
		try {

			Query query = session.createQuery("from Store where id=:ID ");
			query.setInteger("ID", storeID);
			Store store = (Store) query.uniqueResult();
			Set<ProductPrice> prices = (Set<ProductPrice>) store.getPrices();
			System.out.println("Retrieved " + prices.size() + " prices");
			message.writeInt(prices.size());
			for (ProductPrice price : prices) {
				message.writeInt(price.getProduct_id());
				message.writeString(price.getPrice());
				message.writeString(price.getCurrency());
			}
		} catch (HibernateException e) {
			e.printStackTrace();
		} finally {
			session.close();
		}
	}
}
